import { defineStore } from 'pinia'
import { findMenuTree } from '@/api/common'
import config from '@/config'
import baseRouter from '@/router/baseRouter'
import type { Itag } from '@/commonTypes'

export const appStore = defineStore(`${config.sysCode}_app`, {
  state: (): any => {
    return {
      asyncMenus: [],
      localRoutersMap: {},
      navTags: [{ name: 'home', title: '检验工作桌面' }]
    }
  },
  persist: {
    enabled: true,
    strategies: [{ storage: sessionStorage, paths: ['navTags'] }]
  },
  actions: {
    getAsyncMenus() {
      findMenuTree()
        .then((res) => {
          const { isSuccess, errorMsg, errmsg, data } = res || {}
          if (isSuccess) {
            const localMenus = [...baseRouter]
            this.localRoutersMap = this.getLocalRouterMap(localMenus)
            // 本地路由与接口获取的菜单路由作匹配，匹配成功的则为该用户可操作的菜单
            this.asyncMenus = this.getMenusWithPermission(data, {})
            console.log('asyncMenus', this.asyncMenus)
          } else {
            console.log(errorMsg || errmsg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 递归处理， 枚举本地路由
    getLocalRouterMap(routers: any, routerMap: any = {}) {
      const _routerMap = routerMap
      routers.forEach((item: any) => {
        _routerMap[item.name] = item
        if (item.children) {
          this.getLocalRouterMap(item.children, _routerMap)
        }
      })
      return _routerMap
    },
    // 本地路由与异步菜单路由匹配以及数据结构处理
    getMenusWithPermission(asyncMenus: any, parentRouter) {
      let menuList: any = []
      if (asyncMenus && asyncMenus.length) {
        asyncMenus.forEach((menu: any, index: number) => {
          // 只处理检验系统和监察系统的菜单
          if (menu.sysCode === 'scdeap' || menu.sysCode == 'supervise') {
            const curRoutersMap = this.localRoutersMap[menu.href] // 取出与当前菜单匹配的本地路由
            if (curRoutersMap) {
              // 使用匹配的本地路由，将菜单递归构造成路由结构
              const { meta, component } = curRoutersMap
              const curMenuItem = {
                icon: menu.icon || (meta && meta.icon) || '',
                name: menu.href,
                meta: {
                  title: menu.name,
                  id: menu.id,
                  parentId: menu.parentId,
                  parentIds: menu.parentIds
                },
                component,
                children: this.getMenusWithPermission(menu.childList, curRoutersMap)
              }
              menuList.push(curMenuItem)
            } else {
              if (menu.href && menu.href.indexOf('isTurnByHref') != -1) {
                menuList.push({
                  icon: menu.icon || '',
                  name: menu.href,
                  meta: {
                    title: menu.name,
                    icon: menu.icon
                  }
                })
              }
            }
          }
        })
      }

      return menuList
    },
    // 页签推入处理，已做可持续化存储
    handleNavTagsAdd(navTag: Itag) {
      if (this.navTags.every((tag: Itag) => tag.name !== navTag.name)) {
        this.navTags.push(navTag)
      }
    },
    NavTagsResetHandle() {
      this.navTags = [{ name: 'home', title: '检验工作桌面' }]
    }
  }
})
